fetch api是現代 JavaScript 用於進行網路請求的接口。發送請求後,通過 fetch() 從伺服器獲取資料。以下為基本fetch程式碼
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
//想抓取的資料
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
要抓取的主要內容寫在.then(data => {})這裡面,而第一段.then(response=>{})主要是將返回的數據解析為 JSON 格式,最後一段則是處理錯誤。
以上為fetch api的基本格式,今天的介紹就先到這啦~~![]()